package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    private final WeChatProperties weChatProperties;
    private final UserMapper userMapper;
    private final JwtProperties jwtProperties;

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public UserServiceImpl(WeChatProperties weChatProperties, UserMapper userMapper, JwtProperties jwtProperties){
        this.weChatProperties = weChatProperties;
        this.userMapper = userMapper;
        this.jwtProperties = jwtProperties;
    }
    @Override
    public UserLoginVO wxLogin(String code) {

        HashMap<String,String> param = new HashMap<>();
        param.put("appid",weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        String res = HttpClientUtil.doGet(WX_LOGIN_URL,param);

        JSONObject json = JSONObject.parseObject(res);
        String openid = (String) json.get("openid");

        if(openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }


        //根据openid查用户表
        User user = userMapper.getByOpenid(openid);

        if(user == null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.insert(user);
        }

        HashMap<String, Object> clams = new HashMap<>();
        clams.put("openid", user.getOpenid());

        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),clams);
        UserLoginVO userLoginVO = UserLoginVO.builder().openid(openid).id(user.getId()).token(token).build();


        return userLoginVO;
    }
}
